#!/bin/bash
set -e
export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.nvm/current/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

# Resolve PropPairAI-Mac root directory whether launched from .app or .command
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ "$SELF_DIR" == *".app/Contents/MacOS" ]]; then
  PKG_ROOT="$(cd "$SELF_DIR/../../.." && pwd)"
else
  PKG_ROOT="$SELF_DIR"
fi
RUNTIME_SRC="$PKG_ROOT/.runtime"

if [ ! -d "$RUNTIME_SRC/dist" ]; then
  osascript -e 'display alert "PropPairAI Installer" message "Could not find .runtime files. Please extract the entire PropPairAI-Mac-Installer.zip folder first, then double-click Install PropPairAI." as critical'
  exit 1
fi

# Step 1: Native macOS Welcome & DPDP Act Confirmation Dialog
CHOICE=$(osascript -e 'button returned of (display dialog "Welcome to PropPairAI v3.1.21 for macOS!\n\n• 100% Local On-Device Chat Deal Matchmaker\n• Strict Zero-Ban Passive Read-Only Listener\n• India DPDP Act, 2023 Compliant\n• Includes 1 Mobile Home Screen (iPhone & Android)\n\nClick Install & Launch to set up PropPairAI on your Mac." with title "PropPairAI — macOS Setup" buttons {"Cancel", "Install & Launch"} default button "Install & Launch")' 2>/dev/null || echo "Cancel")

if [ "$CHOICE" != "Install & Launch" ]; then
  exit 0
fi

# Step 2: Locate or Install Node.js v20+ (Universal Apple Silicon + Intel .pkg)
find_node() {
  for candidate in "/opt/homebrew/bin/node" "/usr/local/bin/node" $(ls -dt "$HOME"/.nvm/versions/node/v*/bin/node 2>/dev/null) "$(command -v node 2>/dev/null)"; do
    if [ -x "$candidate" ]; then
      MAJOR=$("$candidate" -p "process.versions.node.split('.')[0]" 2>/dev/null || echo "0")
      if [ "$MAJOR" -ge 20 ] 2>/dev/null; then
        echo "$candidate"
        return 0
      fi
    fi
  done
  return 1
}

NODE_BIN="$(find_node || true)"
if [ -z "$NODE_BIN" ]; then
  INSTALL_NODE=$(osascript -e 'button returned of (display dialog "PropPairAI requires the official Node.js LTS runtime (one-time setup).\n\nClick Download Node.js to automatically download and open the official signed Apple Silicon / Intel installer from nodejs.org." with title "PropPairAI — One-Time Runtime Setup" buttons {"Cancel", "Download Node.js"} default button "Download Node.js")' 2>/dev/null || echo "Cancel")
  if [ "$INSTALL_NODE" != "Download Node.js" ]; then
    exit 0
  fi
  TMP_PKG="/tmp/PropPairAI-Node-v22.14.0.pkg"
  curl -fL "https://nodejs.org/dist/v22.14.0/node-v22.14.0.pkg" -o "$TMP_PKG"
  open -W "$TMP_PKG"
  rm -f "$TMP_PKG"
  export PATH="/usr/local/bin:/opt/homebrew/bin:$PATH"
  NODE_BIN="$(find_node || true)"
  if [ -z "$NODE_BIN" ]; then
    osascript -e 'display alert "Node.js Setup Incomplete" message "Node.js v20+ was not detected yet. Please finish the Node.js installer window and run Install PropPairAI again." as warning'
    exit 1
  fi
fi

NODE_DIR="$(dirname "$NODE_BIN")"
NPM_BIN="$NODE_DIR/npm"
export PATH="$NODE_DIR:$PATH"

# Step 3: Copy runtime to ~/Library/Application Support/PropPairAI (preserving existing data/ & local_wa_auth/)
APP_DATA_DIR="$HOME/Library/Application Support/PropPairAI"
mkdir -p "$APP_DATA_DIR" "$APP_DATA_DIR/data" "$APP_DATA_DIR/exports" "$APP_DATA_DIR/logs"

# Stop existing server on :3000 cleanly before updating files
EXISTING_PID=$(lsof -ti tcp:3000 2>/dev/null || true)
if [ -n "$EXISTING_PID" ]; then
  kill $EXISTING_PID 2>/dev/null || true
  sleep 1
fi

rm -rf "$APP_DATA_DIR/dist"
cp -R "$RUNTIME_SRC/dist" "$APP_DATA_DIR/dist"
cp "$RUNTIME_SRC/package.json" "$APP_DATA_DIR/package.json"
cp "$RUNTIME_SRC/package-lock.json" "$APP_DATA_DIR/package-lock.json"
cp "$RUNTIME_SRC/license_public.pem" "$APP_DATA_DIR/license_public.pem"
if [ ! -f "$APP_DATA_DIR/.env" ]; then
  cp "$RUNTIME_SRC/.env" "$APP_DATA_DIR/.env"
fi
if [ -f "$RUNTIME_SRC/logo.png" ]; then
  cp "$RUNTIME_SRC/logo.png" "$APP_DATA_DIR/logo.png"
fi
xattr -cr "$APP_DATA_DIR" 2>/dev/null || true

# Step 4: Install native macOS dependencies (better-sqlite3 prebuilt binary for arm64 / x64)
osascript -e 'display notification "Installing local database engine & configuring macOS shortcuts..." with title "PropPairAI Setup"' 2>/dev/null || true
cd "$APP_DATA_DIR"
"$NPM_BIN" install --omit=dev --no-audit --no-fund

# Step 5: Build native macOS Icon (.icns) from logo.png using built-in sips + iconutil
ICNS_PATH="$APP_DATA_DIR/AppIcon.icns"
if [ -f "$APP_DATA_DIR/logo.png" ] && command -v sips >/dev/null 2>&1 && command -v iconutil >/dev/null 2>&1; then
  ICONSET_TMP="/tmp/PropPairAI.iconset"
  rm -rf "$ICONSET_TMP"
  mkdir -p "$ICONSET_TMP"
  sips -z 16 16     "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_16x16.png" >/dev/null 2>&1 || true
  sips -z 32 32     "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_16x16@2x.png" >/dev/null 2>&1 || true
  sips -z 32 32     "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_32x32.png" >/dev/null 2>&1 || true
  sips -z 64 64     "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_32x32@2x.png" >/dev/null 2>&1 || true
  sips -z 128 128   "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_128x128.png" >/dev/null 2>&1 || true
  sips -z 256 256   "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_128x128@2x.png" >/dev/null 2>&1 || true
  sips -z 256 256   "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_256x256.png" >/dev/null 2>&1 || true
  sips -z 512 512   "$APP_DATA_DIR/logo.png" --out "$ICONSET_TMP/icon_256x256@2x.png" >/dev/null 2>&1 || true
  iconutil -c icns "$ICONSET_TMP" -o "$ICNS_PATH" >/dev/null 2>&1 || true
  rm -rf "$ICONSET_TMP"
fi

# Step 6: Create PropPairAI.app & Uninstall PropPairAI.app in /Applications (or ~/Applications) + Desktop
if [ -w "/Applications" ]; then
  TARGET_APPS_DIR="/Applications"
else
  TARGET_APPS_DIR="$HOME/Applications"
  mkdir -p "$TARGET_APPS_DIR"
fi

create_launcher_app() {
  local APP_BUNDLE="$1"
  rm -rf "$APP_BUNDLE"
  mkdir -p "$APP_BUNDLE/Contents/MacOS" "$APP_BUNDLE/Contents/Resources"
  if [ -f "$ICNS_PATH" ]; then
    cp "$ICNS_PATH" "$APP_BUNDLE/Contents/Resources/AppIcon.icns"
  fi
  cat > "$APP_BUNDLE/Contents/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleDisplayName</key>
  <string>PropPairAI</string>
  <key>CFBundleName</key>
  <string>PropPairAI</string>
  <key>CFBundleIdentifier</key>
  <string>com.proppairai.app</string>
  <key>CFBundleVersion</key>
  <string>3.1.21</string>
  <key>CFBundleShortVersionString</key>
  <string>3.1.21</string>
  <key>CFBundleExecutable</key>
  <string>PropPairAI</string>
  <key>CFBundlePackageType</key>
  <string>APPL</string>
  <key>CFBundleIconFile</key>
  <string>AppIcon</string>
  <key>NSHighResolutionCapable</key>
  <true/>
</dict>
</plist>
EOF

  cat > "$APP_BUNDLE/Contents/MacOS/PropPairAI" <<'EOF'
#!/bin/bash
export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.nvm/current/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
APP_DATA_DIR="$HOME/Library/Application Support/PropPairAI"
if ! curl -fsS "http://127.0.0.1:3000/api/health" >/dev/null 2>&1; then
  cd "$APP_DATA_DIR" || exit 1
  NODE_BIN=""
  for candidate in "/opt/homebrew/bin/node" "/usr/local/bin/node" $(ls -dt "$HOME"/.nvm/versions/node/v*/bin/node 2>/dev/null) "$(command -v node 2>/dev/null)"; do
    if [ -x "$candidate" ]; then NODE_BIN="$candidate"; break; fi
  done
  if [ -n "$NODE_BIN" ]; then
    nohup "$NODE_BIN" "$APP_DATA_DIR/dist/server.mjs" >> "$APP_DATA_DIR/logs/mac-daemon.log" 2>> "$APP_DATA_DIR/logs/mac-daemon-err.log" &
    for i in {1..20}; do
      if curl -fsS "http://127.0.0.1:3000/api/health" >/dev/null 2>&1; then break; fi
      sleep 0.5
    done
  fi
fi
open "http://localhost:3000"
EOF
  chmod +x "$APP_BUNDLE/Contents/MacOS/PropPairAI"
  xattr -cr "$APP_BUNDLE" 2>/dev/null || true
}

create_launcher_app "$TARGET_APPS_DIR/PropPairAI.app"
create_launcher_app "$HOME/Desktop/PropPairAI.app"

# Copy Uninstaller into Applications & App Support
if [ -d "$PKG_ROOT/Uninstall PropPairAI.app" ]; then
  rm -rf "$TARGET_APPS_DIR/Uninstall PropPairAI.app"
  cp -R "$PKG_ROOT/Uninstall PropPairAI.app" "$TARGET_APPS_DIR/Uninstall PropPairAI.app"
  if [ -f "$ICNS_PATH" ]; then
    mkdir -p "$TARGET_APPS_DIR/Uninstall PropPairAI.app/Contents/Resources"
    cp "$ICNS_PATH" "$TARGET_APPS_DIR/Uninstall PropPairAI.app/Contents/Resources/AppIcon.icns"
  fi
  xattr -cr "$TARGET_APPS_DIR/Uninstall PropPairAI.app" 2>/dev/null || true
fi
if [ -f "$PKG_ROOT/Uninstall PropPairAI.command" ]; then
  cp "$PKG_ROOT/Uninstall PropPairAI.command" "$APP_DATA_DIR/Uninstall PropPairAI.command"
  chmod +x "$APP_DATA_DIR/Uninstall PropPairAI.command"
fi

# Step 7: Configure macOS LaunchAgent Auto-Start & Start Server Now
LAUNCH_AGENTS_DIR="$HOME/Library/LaunchAgents"
PLIST_PATH="$LAUNCH_AGENTS_DIR/com.proppairai.desktop.plist"
mkdir -p "$LAUNCH_AGENTS_DIR"
launchctl unload "$PLIST_PATH" >/dev/null 2>&1 || true

cat > "$PLIST_PATH" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.proppairai.desktop</string>
  <key>ProgramArguments</key>
  <array>
    <string>$NODE_BIN</string>
    <string>$APP_DATA_DIR/dist/server.mjs</string>
  </array>
  <key>WorkingDirectory</key>
  <string>$APP_DATA_DIR</string>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <false/>
  <key>StandardOutPath</key>
  <string>$APP_DATA_DIR/logs/mac-daemon.log</string>
  <key>StandardErrorPath</key>
  <string>$APP_DATA_DIR/logs/mac-daemon-err.log</string>
</dict>
</plist>
EOF

launchctl load "$PLIST_PATH" >/dev/null 2>&1 || nohup "$NODE_BIN" "$APP_DATA_DIR/dist/server.mjs" >> "$APP_DATA_DIR/logs/mac-daemon.log" 2>> "$APP_DATA_DIR/logs/mac-daemon-err.log" &

for i in {1..24}; do
  if curl -fsS "http://127.0.0.1:3000/api/health" >/dev/null 2>&1; then
    break
  fi
  sleep 0.5
done

open "http://localhost:3000"
osascript -e 'display dialog "✅ PropPairAI v3.1.21 is installed and live at http://localhost:3000!\n\n• App Shortcut added to Applications & Desktop\n• Uninstaller added to Applications (Uninstall PropPairAI)" with title "PropPairAI — Ready" buttons {"Done"} default button "Done"' >/dev/null 2>&1 || true
exit 0
